<template>
    <el-dialog :title="title" v-model="visible" append-to-body :lock-scroll="true" center
        custom-class="RegularPop dialogListPop" @close="cancel" :close-on-click-modal="false">
        <!--查询数据-->
        <div class="SearchTop">
            <el-form :model="queryParams" ref="queryRef" :inline="true">
                <el-row>
                    <el-col :span="8">
                        <el-form-item>
                            <el-button type="primary" plain icon="Plus" @click="handleAdd">
                                新增套餐
                            </el-button>
                            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

        </div>
        <div class="tableList dialog-tableList">
            <el-table :data="tableData" v-loading="loading" style="width: 100%" border class="table-container" stripe
                align="center" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" v-if="!isView"> </el-table-column>
                <el-table-column label="序号" width="60" type="index"> </el-table-column>
                <template v-for="(item, index) in tableHead" :key="index">
                    <el-table-column :prop="item.dataIndex" :label="item.title" :align="center" show-overflow-tooltip>
                        <template #default="scope">
                            <template v-if="item.dataIndex == 'validityPeriod'">
                                <span>{{ scope.row.payTime }} - {{ scope.row.expiredTime }}</span>
                            </template>

                        </template>
                    </el-table-column>
                </template>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="!isView">
                    <template #default="scope">

                        <a v-if="scope.row.serviceStatus == 1" @click="handleDisable(scope.row)" title="禁用">
                            <img src="../../../assets/images/manage/jy.png" alt="" />
                        </a>
                        <a v-if="scope.row.serviceStatus == 0 || scope.row.serviceStatus == 2"
                            @click="handleEnable(scope.row)" title="启用">
                            <img src="../../../assets/images/manage/qy.png" alt="" />
                        </a>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
        <el-dialog title="订购服务" custom-class="RegularPop el-dialog-s" v-model="innerVisible" append-to-body
            :lock-scroll="true" center :show-close="false">
            <el-form :model="form" :rules="rules" ref="newComboForm" :inline="true">
                <h1></h1>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="开通版本" prop="comboId">
                            <el-select v-model="form.comboId" placeholder="请选择" clearable @change="onChangeCombo">
                                <el-option v-for="(dict, index) in comboLists" :key="index" :label="dict"
                                    :value="index" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="销售人员">
                            <el-input v-model="form.sales" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="服务时间">
                            <span>{{ form.lastExpiredTime }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="innerVisible = false">返回</el-button>
                    <el-button type="primary" @click="comboSubmit">确定</el-button>
                </span>
            </template>


        </el-dialog>
    </el-dialog>
</template>
<script setup>
import {
    getComboList, updateTenantComboStatus, tenantAddCombo, delTenantCombo
} from '@/api/tenant/tenant'
import { getComboDic, calculateExpired } from '@/api/tenant/combo'
const { proxy } = getCurrentInstance();
const loading = ref(true);
const multiple = ref(true);
const ids = ref([]);
const single = ref(true);
const title = ref("租户套餐");
const visible = ref(false);
const innerVisible = ref(false);
const comboLists = ref({})
const total = ref(0);
const service = ref(false);
const data = reactive({
    form: {
    },
    queryParams: {
        tenantId: undefined,
        pageNum: 1,
        pageSize: 10,
    },

    tableHead: [
        {
            dataIndex: 'name',
            title: '服务名称',

        },

        {
            dataIndex: 'sales',
            title: '客户经理',

        },

        {
            dataIndex: 'payAmount',
            title: '软件价格',

        },
        {
            dataIndex: 'payType_dictText',
            title: '缴费类型',

        },
        {
            dataIndex: 'paymentMethod_dictText',
            title: '支付方式',

        },
        {
            dataIndex: 'payTime',
            title: '支付时间',

        },
        {
            dataIndex: 'validityPeriod',
            title: '有效期',

        },
        {
            dataIndex: 'serviceStatus_dictText',
            title: '服务状态',

        },
    ],
    tableData: [],
    rules: {
        comboId: [{ required: true, message: "版本不能为空", trigger: "blur" }],
    },
});

const { queryParams, tableHead, tableData, rules, form } = toRefs(data);
function edit(row) {
    //  console.log('row', row);
    visible.value = true;
    queryParams.value.tenantId = row.id;
    tenantCombo(queryParams.value);
}
function tenantCombo(query) {
    //获取租户套餐列表
    loading.value = true
    getComboList(query).then(res => {
        //    console.log('租户套餐liebiao', res)
        if (res.code == 200) {
            tableData.value = res.rows;
            total.value = res.total;
            loading.value = false;
        }
    })
}
function toSplit(str) {
    let arr = str.split(' ')
    console.log(arr)
}
function handleDisable(row) {
    const status = 2;
    const tenantComboId = row.id;
    queryParams.value.tenantId = row.tenantId;
    proxy.$modal.confirm('是否要禁用此套餐？').then(function () {
        return updateTenantComboStatus(tenantComboId, status);
    }).then(() => {
        tenantCombo(queryParams.value);
        proxy.$modal.msgSuccess("套餐已禁用");
    }).catch(() => { });

}

function handleEnable(row) {
    const status = 1;
    const tenantComboId = row.id;
    queryParams.value.tenantId = row.tenantId;
    proxy.$modal.confirm('是否要启用此套餐？').then(function () {
        return updateTenantComboStatus(tenantComboId, status);
    }).then(() => {
        tenantCombo(queryParams.value);
        proxy.$modal.msgSuccess("套餐已启用");
    }).catch(() => { });

}
/** 取消按钮 */
function cancel() {
    queryParams.value = {
        tenantId: undefined,
        pageNum: 1,
        pageSize: 10,
    },
        visible.value = false;

}
/** 重置操作表单 */
function reset() {
    form.value = {};
    proxy.resetForm("passWordForm");
}
function handleAdd() {
    reset();
    innerVisible.value = true;
    getCombos();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
    // console.log('selection', selection)
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
    let serviceType = selection.map(item => item.serviceStatus);
    console.log('serviceType', serviceType)
    for (let i in serviceType) {
        if (serviceType[i] != 1) {
            service.value = false
        } else {
            service.value = true
        }
    }
}
function getCombos() {
    getComboDic().then(res => {
        //  console.log('套餐列表', res)
        if (res.code == 200) {
            comboLists.value = res.data;
        }

    })
}

function onChangeCombo(val) {
    const comboId = val
    calculateExpired(comboId).then(res => {
        if (res.code == 200) {
            form.value.lastExpiredTime = res.data[0] + ' - ' + res.data[1]
        }
    })
}
function handleDelete() {
    const tenantComboIds = ids.value;
    if (service.value == false) {
        proxy.$modal.confirm('是否确认删除此套餐服务？').then(function () {
            return delTenantCombo(tenantComboIds);
        }).then(() => {
            tenantCombo(queryParams.value);
            proxy.$modal.msgSuccess("删除成功");
        }).catch(() => { });
    } else {
        proxy.$modal.confirm('套餐服务中不能删除！')
    }

}
function comboSubmit() {//tenantAddCombo
    proxy.$refs['newComboForm'].validate(valid => {
        if (valid) {
            let data = {
                comboId: form.value.comboId,
                lastExpiredTime: form.value.lastExpiredTime,
                sales: form.value.sales,
                tenantId: queryParams.value.tenantId
            }
            tenantAddCombo(data).then(res => {
                if (res.code == 200) {
                    proxy.$modal.msgSuccess("新增成功");
                    innerVisible.value = false;
                    tenantCombo(queryParams.value)
                }

            })
        } else {
            proxy.$modal.msgError("提交失败！");
            return false;
        }
    })
}

defineExpose({
    edit
});
</script>